using System;
using System.Diagnostics;
using System.Net;
using System.ServiceProcess;
using System.Timers;
using System.Web;
using MySql.Data.MySqlClient;

namespace weatherService
{
  public partial class wService : ServiceBase
  {
    private readonly Timer m_timer;
    private const string m_url = "http://pogoda.open.by/minsk/detail";

    private const string m_weatherTableName = "sl_weather";
    private MySqlConnection conn;

    public wService()
    {
      InitializeComponent();
      int mins = Properties.Settings.Default.TimeOut;
      m_timer = new Timer(TimeSpan.FromMinutes(mins).TotalMilliseconds);
      m_timer.Elapsed += OnTimerElapsed;
    }

    private void OnTimerElapsed(object sender, ElapsedEventArgs e)
    {
      UpdateData();
      m_timer.Start();
    }

    protected override void OnStart(string[] args)
    {
      UpdateData();
      m_timer.Start();
    }

    protected override void OnStop()
    {
      m_timer.Stop();
    }

    private void UpdateData()
    {
      try
      {
        Connect();
        InsertData(ParseWeatherData(m_url));
        EventLog.WriteEntry("Weather stealer", "Weather data parsed and updated successfully.", EventLogEntryType.SuccessAudit);
      }
      catch (Exception ex)
      {
        EventLog.WriteEntry(ex.Message, EventLogEntryType.Error);
      }
    }

    private static string ParseWeatherData(string url)
    {
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
      WebResponse response = request.GetResponse();

      string parsed = OpenByParser.Parse(response.GetResponseStream());
      return HttpUtility.HtmlEncode(parsed);
    }

    private void InsertData(string weatherData)
    {
      const string truncateText = "TRUNCATE TABLE " + m_weatherTableName;
      string insertText = string.Format("INSERT INTO {0} (`weatherData`) VALUES ('{1}');",
                                        m_weatherTableName, weatherData);

      MySqlHelper.ExecuteScalar(conn, truncateText);
      MySqlHelper.ExecuteScalar(conn, insertText);
    }

    private void Connect()
    {
      string connStr = String.Format("server={0};user id={1}; password={2}; database=weather; pooling=false; charset=utf8",
          "10.220.1.101", "weather", "0slo");

      conn = new MySqlConnection(connStr);
      conn.Open();
    }

  }
}
